package com.wxl.multi.redis;


import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.connection.ClusterInfo;
import org.springframework.data.redis.connection.RedisClusterConnection;
import org.springframework.data.redis.connection.RedisClusterNode;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.Map;

@RestController
public class TestController {

//    @Qualifier("cluster1RedisTemplate")
//    RedisTemplate<String, Object> cluster1RedisTemplate;
//    @Qualifier("cluster2RedisTemplate")
//    RedisTemplate<String, Object> cluster2RedisTemplate;

    @Resource(name="cluster1RedisTemplate")
    RedisTemplate<String, String> cluster1RedisTemplate;
    @Resource(name="cluster2RedisTemplate")
    RedisTemplate<String, String> cluster2RedisTemplate;


    @Autowired
    private RedisLock redisLock;

    @Autowired
    private MyService myService;

    @GetMapping("/redis2")
    public String test(@RequestParam String key){

        printClusterInfo();



        Object val1 = cluster1RedisTemplate.opsForValue().get(key);
        System.out.println(val1);

        Object val2 = cluster2RedisTemplate.opsForValue().get(key);
        System.out.println(val2);

        redisLock.lock("wxl-lock","s",1000);


        myService.exampleBatchGetFromCluster1();
        myService.exampleBatchGetFromCluster2();
//        myService2.exampleAsyncBatchGet();

        return "succ";
    }


    private void printClusterInfo(){
        RedisClusterConnection connection = cluster1RedisTemplate.getConnectionFactory().getClusterConnection();
        // 集群基础信息
        ClusterInfo clusterInfo = connection.clusterGetClusterInfo();
        System.out.println("集群基础信息："+ JSON.toJSONString(clusterInfo));

        // 集群主从信息
        Map<RedisClusterNode, Collection<RedisClusterNode>> redisClusterNodeCollectionMap = connection.clusterGetMasterSlaveMap();
        System.out.println("集群主从信息："+ JSON.toJSONString(redisClusterNodeCollectionMap));

        // 每个节点详情
        Iterable<RedisClusterNode> redisClusterNodes = connection.clusterGetNodes();
        redisClusterNodes.forEach(node ->{
            System.out.println("集群每个节点信息："+ JSON.toJSONString(node));
        });

//        找节点
        //io.lettuce.core.cluster.models.partitions.RedisClusterNode partition = this.partitions.getPartitionBySlot(slot);
    }

}
